package com.course.web.component.custom;

import com.course.web.biz.WebCourseBiz;
import com.course.web.biz.WebLearnBiz;
import com.course.web.component.base.BaseGrid;
import com.course.web.component.base.EditGrid;
import com.course.web.model.CourseInfoVM;
import com.course.web.model.LearnStatVM;
import com.course.web.view.CourseListView;
import com.vaadin.spring.annotation.SpringComponent;
import com.vaadin.spring.annotation.ViewScope;
import com.vaadin.ui.Button;
import com.vaadin.ui.DateField;
import com.vaadin.ui.Layout;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDate;

/**
 * Created by Justin on 2017/7/1.
 */
@SpringComponent
@ViewScope
public class LearnStatGrid extends EditGrid<LearnStatVM> {

    private final WebCourseBiz courseBiz;
    private final WebLearnBiz learnBiz;

    private int courseId;
    private LocalDate begin;
    private LocalDate end;
    private DateField dateField;

    @Autowired
    public LearnStatGrid(WebCourseBiz courseBiz, WebLearnBiz learnBiz) {
        super(LearnStatVM.class);
        this.courseBiz = courseBiz;
        this.learnBiz = learnBiz;
    }

    @Override
    protected void doInitMenu(Layout menu) {
        Button back = new Button("返回");
        Button last = new Button("前一天");
        Button next = new Button("后一天");
        dateField = new DateField();
        dateField.setEnabled(false);
        menu.addComponent(back);
        menu.addComponent(last);
        menu.addComponent(dateField);
        menu.addComponent(next);
        back.addClickListener(event -> getUI().getNavigator().navigateTo(CourseListView.NAME));
        last.addClickListener(event -> {
            LocalDate current = dateField.getValue();
            if (current.isAfter(begin)) {
                current = current.minusDays(1);
                enter(courseId, current);
            }
        });
        next.addClickListener(event -> {
            LocalDate current = dateField.getValue();
            if (current.isBefore(end)) {
                current = current.plusDays(1);
                enter(courseId, current);
            }
        });

    }

    @Override
    protected void doInitGrid(BaseGrid<LearnStatVM> grid) {
        grid.addColumn(LearnStatVM::getStudent, "学生");
        grid.addColumn(LearnStatVM::getCourse, "课程");
        grid.addColumn(LearnStatVM::getTotal, "任务总数");
        grid.addColumn(LearnStatVM::getDone, "任务完成");
    }

    public void enter(int courseId, LocalDate today) {
        CourseInfoVM info = courseBiz.loadInfo(courseId);
        this.courseId = courseId;
        begin = info.getDate();
        end = begin.plusWeeks(info.getWeeks());
        dateField.setValue(today);
        init(learnBiz.findStat(courseId, today));
    }
}
